package com.example.photoutil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;


import com.bumptech.glide.Glide;

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import androidx.core.content.FileProvider;

public class PhotoUtils {


    public static File getImageFile(Context context) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = timeStamp + ".jpg";
        File mediaFile = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File file = new File(mediaFile, imageFileName);
        if (file.exists()) {
            file.delete();
        }
        return file;
    }

    public static Uri getFileUri(Context context, File file) {


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// sdk >= 24  android7.0以上
            Uri contentUri = FileProvider.getUriForFile(context,
                    "com.example.photoutil.provider",//与清单文件中android:authorities的值保持一致
                    file);//FileProvider方式或者ContentProvider。也可使用VmPolicy方式
            return contentUri;

        } else {
            return Uri.fromFile(file);//或者 Uri.isPaise("file://"+file.toString()
        }
    }

    /**
     * @param activity    当前activity
     * @param orgUri      剪裁原图的Uri
     * @param file        剪裁后的图片的Uri(Uri.fromFile(file))
     * @param aspectX     X方向的比例
     * @param aspectY     Y方向的比例
     * @param width       剪裁图片的宽度
     * @param height      剪裁图片高度
     * @param requestCode 剪裁图片的请求码
     */
    public static void cropImageUri(Activity activity, Uri orgUri, File file, int aspectX, int aspectY, int width, int height, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(orgUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        intent.putExtra("outputX", width);
        intent.putExtra("outputY", height);
        intent.putExtra("scale", true);
        //将剪切的图片保存到目标Uri中
        Uri uri = Uri.fromFile(getImageFile(activity));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, requestCode);

    }

    /**
     * 按比例展示缩略图
     * file ：图片文件
     * sampleSize :缩放比例 1 为原始尺寸 ↑为缩放
     */
    public static Bitmap showBitmap(File file, int sampleSize) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = sampleSize;
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

        Log.i(file.getName(), bitmap.getWidth() + "/" + bitmap.getHeight());
        return bitmap;
    }


    public static void cropGlide(MainActivity mainActivity, Uri uri,int x,int y) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = Glide.with(mainActivity).load(uri).asBitmap().centerCrop().into(x, y).get();
                    File file = PhotoUtils.getImageFile(mainActivity);
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                    //保存图片后发送广播通知更新数据库
                    Uri uri1 = Uri.fromFile(file);
                    mainActivity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri1));
                    Message message = Message.obtain();
                    message.obj = bitmap;
                    mainActivity.handler.sendMessage(message);
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
